# Title     : TODO
# Objective : TODO
# Created by: Administrator
# Created on: 2019/8/12
library(optparse)
library(tidyverse)
library(DescTools)

gg_color_hue <- function(n) {
  hues = seq(15, 375, length = n + 1)
  hcl(h = hues, l = 65, c = 100)[1:n]
}

getClassCols <- function(n) {
  inCols <- c("#00FFFF", "#0099FF", "#8A4198", "#FF6F00", "#CC9999", "#FFFF00", "#00FF7F", "#999999", "#CCFFCC", "#336666",
              "#FF6666", "#FFCC33", "#CC3399")
  extraColors <- c("#CD0000", "#3A89CC", "#769C30", "#D99536", "#7B0078", "#BFBC3B", "#6E8B3D", "#00688B", "#C10077", "#CAAA76",
                   "#EEEE00", "#458B00", "#8B4513", "#008B8B", "#6E8B3D", "#8B7D6B", "#7FFF00", "#CDBA96", "#ADFF2F")
  orignalCols <- c(inCols, extraColors)
  on <- length(orignalCols)
  if (n <= on) {
    orignalCols[1:n]
  }else {
    ggCols <- gg_color_hue(n - on)
    c(orignalCols, ggCols)
  }
}

option_list <- list(
  make_option("--i", default = "AllMet1.csv", type = "character", help = "metabolite data file"),
  make_option("--g", default = "SampleInfo.csv", type = "character", help = "sample group file"),
  make_option("--cp", default = "", type = "character", help = "compare info "),
  make_option("--sc", default = "sample_color.txt", type = "character", help = "sample color file")
)
opt <- parse_args(OptionParser(option_list = option_list))

groups <- unlist(strsplit(opt$cp, "_vs_"))
groups

sampleColDf <- read_csv(opt$sc)

colorData <- groups %>%
  map_dfr(function(group) {
    totalCol <- sampleColDf %>%
      filter(ClassNote == group) %>%
      .$col
    finalColor <- if (length(totalCol)==0) {
      inGroups <- unlist(strsplit(group, "\\+"))
      color <- ""
      for (inGroup in inGroups) {
        inColor <- sampleColDf %>%
          filter(ClassNote == inGroup) %>%
          .$col
        if (color == "") {
          color <- inColor
        }else {
          color <- MixColor(color, inColor, 0.5)
        }
      }
      color
    }else totalCol

    return(data.frame(ClassNote = group, col = finalColor))
  })

head(colorData)

write_csv(colorData, "Class_Color.csv")

classes <- read.csv(opt$i, header = T, stringsAsFactors = F) %>%
  .$Class %>%
  unique()

classCols <- getClassCols(length(classes))
classColDf <- data.frame(Class = classes, col = classCols)
write.table(classColDf, "meta_color.txt", sep = "\t", col.names = NA, quote = FALSE)


